<?php
require_once('BaseController.php');

/**
 * Sites
 * @author Gedalias
 * @name Sites
 * @label Sites
 * @menu 1
 * @menu_secao Administra&ccedil;&atilde;o
 */

class Third_SitesController extends BaseController
{
	protected $name = 'sites';
	protected $configFile = 'third_sites';
	protected $dao;

	public function init(){
		parent::init();

		//LOAD DAO
		require_once('Sites.php');
		$this->dao = new Sites();
	}
	
	/**
	 * Listar sites
	 * @order 1
	 * @menu 1
	 */
	public function indexAction()
	{
		$grid = new Third_Grid();

		//COLUMNS
		$columns = $this->getColumns();
		if( is_array( $columns ) ){
			foreach( $columns as $key=>$data){
				$grid->addColumn( $data );		
			}
		}

		$gridOptions = $this->getGridOptions();
		$this->view->moduleTitle = $gridOptions['caption'];

		$data = $this->getSitesData();

		$this->view->assign('sites', $data );
		
		//LOG OPERATIONS
		$this->log('list');
	}

	/**
	 * Editar site
	 * @return unknown_type
	 */
	public function editAction( ){
		$this->view->assign('moduleTitle', $this->configs->moduleTitle );

		$id = $this->getRequest()->getParam('id');
		$data = array();

		if( $id ){
			$form = $this->getFormProfile();
			$form->setAction( '/third/'.$this->name.'/edit/id/'.$id );
			$form->getElement('profile')->setAttribs(array('readonly'=>'true', 'disabled'=>'true') );

			if( $this->getRequest()->isPost() ){

				$data = $this->getRequest()->getPost();

				//VALIDATE FORM
				if( $form->isValid( $data ) ){

					$saveData = array(
						'empresa'=>$data['empresa'],
						'titulo'=>$data['titulo'],
						'profile'=>$data['profile'],
						'urls'=>Third_Funcs::getLinksJson( $data['urls'] )
					);

					try{
						//Verifica se o usuario tem permissao para cadatrar usuario com o nivel informado
						if( !$this->isAdmin() )
							$whereSiteId = " AND sites_id = ".$this->_logged->sites_id ;

						$idSave = $this->db->quote( $id );
						$where = ('id = '.$idSave.$whereSiteId );
						$objetoId = $this->dao->update( $saveData, $where );

						//LOG OPERATIONS
						$this->log('update', 'SUCCESS', $this->dao->getName(), $id );

						$this->flash('Site atualizado com sucesso.', 'success', '/third/'.$this->name.'/edit/id/'.$id );

					} catch( Zend_Exception $e ){
						//LOG OPERATIONS
						$this->log('update', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );
	
						$this->flash('Erro ao atualizar site. Tente novamente.', 'error', '/third/'.$this->name );
					}
				}else{
					$this->view->assign('formErro','Por favor, verifique os erros informados.');
					$form->populate( $data );
				}
			}

			//RETORNA USUARIO DO BANCO DE DADOS
			$site = $this->dao->getById( $id );
			
			$mainLink = Third_Funcs::getMainLink( $site['urls'] );
			$this->view->assign('mainLink', $mainLink );

			//PRIVILEGIOS DO SITE
				require_once("PrivilegiosSites.php");
				$privilegiosSitesDao = new PrivilegiosSites();

				if( $this->cache->test('grupos_privilegios_sites_'.$id) ){
					$privilegegioDoSite = $this->cache->load('grupos_privilegios_sites_'.$id);
				} else {
					$privilegegioDoSite = $privilegiosSitesDao->getByNivelWithModules( $id );
					$this->cache->save($privilegegioDoSite, 'grupos_privilegios_sites_'.$id, array('grupos', 'privilegios', 'sites'));
				}

					$privileges = array();
					foreach( $privilegegioDoSite as $p ){
						$privileges[] = $p['regra']; 
					}
					$this->view->assign('privileges', $privileges );

			//END PRIVILEGIOS DO SITE		


			// USUARIOS DO SITE
				require_once("Usuarios.php");
				$usuariosDoSite = new Usuarios();
				$select = $usuariosDoSite->getSelectObject()->where('sites_id = ?', $site['id']);
				$usuariosDoSite->setSelectObject( $select );

				$usuarios = $usuariosDoSite->getAll();
				$this->view->assign('usuarios', $usuarios );

			// USUARIOS DO SITE
					
			if( $site ){
				$this->view->assign('site', $site );
				$site['urls'] = Third_Funcs::getLinksLines( $site['urls'] );
				$form->populate( $site );
			}

			$form->setAttrib('class','forms' );
			$this->view->assign('form',$form );

		} else {
			//LOG OPERATIONS
			$this->log('edit', 'CRITICAL_DB_SELECT_ERROR', $this->dao->getName(), $id );

			$this->flash('Site inexistente. Tente novamente.', 'error', '/third/'.$this->name );	
		}

		//LOG OPERATIONS
		$this->log('form','',$this->dao->getName(), $id );
	}
	
	/**
	 * Adicionar usuario ao site
	 */
	public function adicionarUsuarioAoSiteAction(){
		require_once("Usuarios.php");
		$usuariosDoSite = new Usuarios();
		$usuariosDoSite->setUserType( 'sistema_cliente' );

		$id = $this->getRequest()->getParam('id');
		$site_id = $this->getRequest()->getParam('site');
		$profile = $this->getRequest()->getParam('profile');
		$ac = $this->getRequest()->getParam('ac');
		
		$this->view->assign('site_id', $site_id );

		$site = $this->_logged->sites_id;
		if($id){
			
			try{				
				$usuario = $usuariosDoSite->getById( $id );

				if( $this->isAdmin() ){
					$site = $site_id;
				} elseif( $usuario['sites_id'] != $site){
					//LOG OPERATIONS
					$this->log('update', 'CRITICAL_HACKED_OPERATION', $usuariosDoSite->getName(), $id );
					$this->flash('Erro ao associar usuario.', 'error', '/third/'.$this->name.'/edit/id/'.$site_id );
				}
				
				$msg = "";
				if( $ac == 'excluir'){
					$site = $this->_logged->sites_id;
					$msg = "Usuario excluido com sucesso.";
				}

				$data = array(
					'sites_id'=>$site
				);

				$usuariosDoSite->update( $data, "id = '".$id."'");

				//LOG OPERATIONS
				$this->log('update', 'SUCCESS', $usuariosDoSite->getName(), $id );
	
				if( !$msg )
					$msg = 'Usuario adicionado com sucesso.';

				$this->flash( $msg , 'success', '/third/'.$this->name.'/edit/id/'.$site_id );
	
			} catch( Zend_Exception $e ){
				//LOG OPERATIONS
				$this->log('update', 'CRITICAL_DB_UPDATE_ERROR', $usuariosDoSite->getName() );
	
				$this->flash('Erro ao adicionar usuario ao site. Tente novamente.', 'error', '/third/'.$this->name.'/edit/id/'.$site_id );
			}
		}
		// USUARIOS DO SITE
			$select = $usuariosDoSite->getSelectObject()->where('sites_id = ?', $site );
			$usuariosDoSite->setSelectObject( $select );

			$usuarios = $usuariosDoSite->getAllBySite();
			$this->view->assign('usuarios', $usuarios );
				
	}
	
	
	/**
	 * Conceder/Regogar privilegios
	 */
	public function privilegiosAction( $privilegios = NULL ){

		require_once("PrivilegiosSites.php");
		$privilegiosDao = new PrivilegiosSites();

		$privilegios = $this->getRequest()->getParam('modules');
		$id = $this->getRequest()->getParam('id');

		$where = $this->db->quoteInto("sites_id = ?", $id );
		$privilegiosDao->delete( $where );


		$this->cache->clean( 
    		Zend_Cache::CLEANING_MODE_MATCHING_TAG,
			array('grupos', 'privilegios', 'sites')
		);

		try{
			$controllers = $this->getControllersDoSistema();

			if( $privilegios ){
				foreach( $privilegios as $regra ){
					$requestOptions = explode(':', $regra );
					
					$menu = "";
					$descricao = "";
					$menu_secao = "";
					$label = "";
					$order = "2";

					if(isset($requestOptions[0])) {
						$module = $requestOptions[0];
						$options  = $controllers[$module];
					} else $module = "";
					
					if(isset($requestOptions[1])) { 
						$controller = $requestOptions[1];
						$options = $options[Ucfirst( $controller )]; 
					} else $controller = "";
					
					if(isset($requestOptions[2])){
						$action = $requestOptions[2];
						$options = $options['controllers'][$action];
					} else $action = "";

					if( isset($options['order']) )
						$menu = $options['order'];

					if( isset($options['menu']) )
						$menu = $options['menu'];

					if( isset( $options['desc'] ) )
						$descricao = $options['desc'];

					if( isset( $options['menu_secao'] ) )
						$menu_secao = $options['menu_secao'];
						
					if( isset( $options['label'] ) )
						$label = $options['label'];

					$data = array(
						'sites_id'=>$id,
						'regra'=>$regra,
						'module'=>$module,
						'controller'=>$controller,
						'action'=>$action,
						'descricao'=>$descricao,
						'menu'=>$menu,
						'label'=>$label,
						'order'=>$order,
						'menu_secao'=>$menu_secao
					);
					$query = ("
					REPLACE INTO 
						`sites_privilegios` (`sites_id`, `regra`, `module`, `controller`, `action`, `descricao`, `menu`, `label`, `menu_secao`, `order`) 
					VALUES 
						('".$id."', '".$regra."', '".$module."', '".$controller."', '".$action."', '".$descricao."', '".$menu."', '".$label."', '".$menu_secao."', '".$order."')
					");

					$privilegiosDao->getDb()->query( $query );
				}
			}
			echo true;
		} catch(Zend_Exception $e ){
			echo $e->getMessage();
		}

		$this->disableViewRender();
		$this->disableLayout();
	}
	
	/**
	 * Remover sites
	 * @return unknown_type
	 */
	public function deleteAction( ){
		$this->view->assign('moduleTitle',$this->configs->moduleTitle );

		$id = $this->getRequest()->getParam('id');
		$confirm = $this->getRequest()->getParam('confirm');

		if( $confirm ){
			$data = $this->getRequest()->getPost();

			//VALIDATE FORM
				$saveData = array(
					'status'=>'2',
					'removido_em' => Third_Funcs::getDate('now','datetime')
				);

				try{
					//Verifica se o usuario tem permissao para cadatrar usuario com o nivel informado
					if( !$this->isAdmin() )
						$whereSiteId = " AND sites_id = ".$this->_logged->sites_id ;

					$idSave = $this->db->quote( $id );
					$where = ('id = '.$idSave.$whereSiteId );
					$objetoId = $this->dao->update( $saveData, $where );

					//LOG OPERATIONS
					$this->log('delete', 'SUCCESS', $this->dao->getName(), $id );

					$this->flash('Site removido com sucesso.', 'success', '/third/'.$this->name );

				} catch( Zend_Exception $e ){
					//LOG OPERATIONS
					$this->log('delete', 'CRITICAL_DB_DELETE_ERROR', $this->dao->getName(), $id );

					$this->flash('Erro ao excluir o site. Tente novamente.', 'error', '/third/'.$this->name );
				}
		}

		//RETORNA USUARIO DO BANCO DE DADOS
		$site = $this->dao->getById( $id );

		if( $site ){
			$this->view->assign('site', $site );
		}

		//LOG OPERATIONS
		$this->log('delete_call', '', $this->dao->getName(), $id );
	}

	/**
	 * Bloquear/Liberar site
	 * @return unknown_type
	 */
	public function unlockAction( ){
		$this->view->assign('moduleTitle',$this->configs->moduleTitle );

		$id = $this->getRequest()->getParam('id');
		//RETORNA USUARIO DO BANCO DE DADOS
		$site = $this->dao->getById( $id );


		if( $site ){
			$this->view->assign('site', $site );
				
				if( $site['status'] == "1"){
					$status = 0;
				} else {
					$status = 1;
				}
			
				//VALIDATE FORM
				$saveData = array(
					'status'=>$status
				);

				try{
					//Verifica se o usuario tem permissao para cadatrar usuario com o nivel informado
					if( !$this->isAdmin() )
						$whereSiteId = " AND sites_id = ".$this->_logged->sites_id ;

					$idSave = $this->db->quote( $id );
					$where = ('id = '.$idSave.$whereSiteId );

					$objetoId = $this->dao->update( $saveData, $where );

					//LOG OPERATIONS
					$this->log('update', 'SUCCESS', $this->dao->getName(), $id );

					$this->flash('Opera&ccedil;&atilde;o realizada com sucesso.', 'success', '/third/'.$this->name.'/edit/id/'.$id );

				} catch( Zend_Exception $e ){
					//LOG OPERATIONS
					$this->log('update', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName(), $id );

					$this->flash('N&atilde;o foi poss&iacute;vel realizar a opera&ccedil;&atilde;o. Tente novamente', 'error', '/third/'.$this->name );
				}
		}

		//LOG OPERATIONS
		$this->log('update', '', $this->dao->getName(), $id );
		
		$this->flash('Site inexistente. Tente novamente', 'error', '/third/'.$this->name );
	}

	/**
	 * Adiciona site
	 * @return unknown_type
	 * @menu 1
	 */
	public function addAction( ){
		$this->view->assign('moduleTitle',$this->configs->moduleTitle );

		$form = $this->getFormProfile();
		$form->setAction( '/third/'.$this->name.'/add' );

		if( $this->getRequest()->isPost() ){
			
			$data = $this->getRequest()->getPost();
			$login 	 = $this->getRequest()->getParam('login');

			//VALIDATE FORM
			if( $form->isValid( $data ) ){
				$profile = $data['profile'];
				
				$saveData = array(
					'empresa'=>$data['empresa'],
					'titulo'=>$data['titulo'],
					'usuarios_id'=>$this->_logged->id,
					'profile'=>$profile ,
					'urls'=>Third_Funcs::getLinksJson( $data['urls'] ),
					'status'=>0,
					'criado_em' => Third_Funcs::getDate('now','datetime')
				);

			try{
					//TODO Verificar se o usuario tem permissao para cadatrar usuario com o nivel informado
					$objetoId = $this->dao->insert( $saveData );

					if( $objetoId ){
						
						//RETORNA OS PRIVILEGIOS DO PROFILE
						require_once("Privilegios.php");
						$privilegiosDao = new Privilegios();

						if( $this->cache->test('grupos_privilegios_'.$profile) ){
							$privilegegioDoUsuario = $this->cache->load('grupos_privilegios_'.$profile);
						} else {
							$privilegegioDoUsuario = $privilegiosDao->getByNivelWithModules( $profile );
							$this->cache->save($privilegegioDoUsuario, 'grupos_privilegios_'.$profile, array('grupos', 'privilegios', $profile));
						}

						// SALVA OS PRIVILEGIOS DO SITE
						require_once("PrivilegiosSites.php");
						$privilegiosSitesDao = new PrivilegiosSites();

						if( $privilegegioDoUsuario ){
							foreach( $privilegegioDoUsuario as $prv ){
								unset($prv['nivel']);
								$prv['sites_id'] = $objetoId;
								//ADD PRIVILEGE
								$privilegiosSitesDao->insert( $prv );
							}
						}
					}

					//LOG OPERATIONS
					$this->log('insert', 'SUCCESS', $this->dao->getName(), $objetoId );
					
					$this->flash('Site cadastrado com sucesso.', 'success', '/third/'.$this->name.'/edit/id/'.$objetoId );

				} catch( Zend_Exception $e ){
					//LOG OPERATIONS
					$this->log('insert', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );

					$this->flash('Erro ao cadastrar o site. Tente novamente.', 'error', '/third/'.$this->name );
				}
			}else{
				$this->view->assign('formErro','Por favor, verifique os erros informados.');
				$form->populate( $data );
			}
					
		}

		$form->removeElement('id');
		$form->setAttrib('class','forms' );
		$this->view->assign('form',$form );

		//LOG OPERATIONS
		$this->log('form');
	}

	public function getGruposIsProfile(){
		
		require_once('Grupos.php');
		$daoGrupos = new Grupos();
		
		/* DADOS DO GRUPO QUE SAO PROFILES */
		$daoGrupos->setQuantidadePaginacao( 50 );
		$select = $daoGrupos
						->getSelectObject()
						->where('status != ?', 2)
						->where('profile = ?', 1);

		$paiData = $daoGrupos->getAll();
		$dataPai[0] = "Selecione um perfil";
		if( count($paiData ) ){
			foreach( $paiData as $data ){
				$dataPai[ $data['nivel'] ] = $data['nome'];
			}
		}
		unset($daoGrupos);
		return $dataPai;
	}

	/**
	 * Pega profile do formularios de acesso
	 * @return Third_Form
	 */
	public function getFormProfile(){
	    //FORMULARIO DE LOGIN
		$formLogin = null;

		$formConfig = $this->configs->form;

		if( $formConfig ){
			
			$form = new Third_Form( $formConfig );
			
			/* DADOS DO GRUPO PAI */
			$dataProfiles = $this->getGruposIsProfile();
			$form->getElement('profile')->setMultiOptions( $dataProfiles );
		} 

		return $form;
	}
	
	/**
	 * Retorna usuarios
	 * @return $paginator
	 */
	public function getSites(){
		$this->dao->setPage( $this->getRequest()->getParam('page', 0 ) );
		
		$search = $this->getRequest()->getParam('search'); 
		$pagesize = $this->getRequest()->getParam('pagesize');
		$index  = $this->getRequest()->getParam('sidx'); 
		$order  = $this->getRequest()->getParam('sord'); 

		//INDEX
		$select = $this->dao->getSelectObject();

		if( $index ) 
			$select->order( array( $index.' '.$order ));

		//QUANTIDADE DE REGISTROS
		if( $pagesize ){ 
			$this->dao->setQuantidadePaginacao( $pagesize );
			$this->view->assign('pagesize', $pagesize );
		}

		//BUSCA
		if( $search ){
			$select->where('nome LIKE "%'.$search.'%"');	
			$this->view->assign('search', $search );
		}
		
		$select->where("status != ?", 2);
		
		if( !$this->isAdmin() )
			$select->where('usuarios_id', $this->_logged->id);

		//EXECUTA
		$this->dao->setSelectObject( $select );
		
		return $this->dao->getAllWithPaginator();
	}
	
	public function getSitesData(){
		$sitesList = $this->getSites();
		$pages = $sitesList->getPages();

		$data = array();
		//PAGES OPTIONS
		$data['page'] = $pages->current;
		$data['total'] = $pages->pageCount;
		$data['records'] = $pages->totalItemCount;

		$this->view->assign('paginator', $sitesList );

		//COLUMNS E ROWS
		$sites = array();
		
		//COLUMNS
		$columns = $this->getColumns();
		$i=0;
		foreach( $sitesList as $key=>$site ){
			$sites[$i]['id'] = $site['id'];
			
			if( is_array($columns) ){
				foreach( $columns as $col=>$value ){
					//USER HEADER
					$data['headers'][$col] = $value;

					if( $col != 'gridEditOptions' ){
						if( $col == 'urls'){
							$sites[$i][$col] = Third_Funcs::getAllLinksFormated( $site[$col] );
						} else {
							$sites[$i][$col] = $site[$col];
						}
					}
				}
				$sites[$i]['fullData'] = Third_Funcs::toArray( reset( $site ) );

				$sites[$i]['GridEditOptions'] = $this->getGridEditOptions( $site['id'] );
			}
			$i++;
		}

		$data['data'] = $sites;

		return $data;
	}

	public function getGridEditOptions( $id = '' ){

			$cont ="<ul id='icons' >";
			$cont .= "<li class='ui-state-default ui-corner-all'><a href='/third/".$this->name."/edit/id/".$id."' title='Editar' class='ui-icon tooltip edit ui-icon-pencil'>Editar</span></a></li>"; 
			$cont .= "<li class='ui-state-default ui-corner-all'><a href='/third/".$this->name."/view/id/".$id."' title='Visualizar' class='ui-icon tooltip view ui-icon-zoomin' >Visualizar</span></a></li>"; 
			$cont .= "<li class='ui-state-default ui-corner-all'><a href='/third/".$this->name."/delete/id/".$id."' title='Excluir' class='ui-icon tooltip delete ui-icon-minus' >Excluir</a></span></li>"; 
			$cont .="</ul>";

			return $cont;		
	}

	/**
	 * Lista sites em formato Json
	 * @return unknown_type
	 */
	public function listJsonAction(){
		$data = $this->getUsuariosData();

		echo json_encode( $data );

		//DISABLE VIEW
		$this->disableLayout();
		$this->disableViewRender();
		
		//LOG OPERAIONS
		$this->log('list');
	}
}

	